﻿CREATE PROCEDURE [dbo].[SupplierReturnLinesUpdate]
(
	@PartyId int, --идентификатор возвращяемой партии. Первично по отношению к @ReturnLineId
	@Qntty int,
	@RetailSum decimal(19, 2),
	@Note varchar(250),
	@MD datetime,
	@MW varchar(50),
	@Original_Id int,
	@Original_MD datetime
)
AS
DECLARE @strMsg nvarchar(500), @intRet int, @intErrCode int
DECLARE @intDocTypeId int, @intDocContragentId int, @intPartyContragentId int
DECLARE @datDocDate smalldatetime, @datInputDocDate smalldatetime
DECLARE @intInputLineId int, @intInputDocId int, @ReturnLineId int --идентификатор возвращяемой строки приходного документа
DECLARE @orgDocId int, @orgPartyId int, @orgQntty int, @intInputCount int, @intOutputCount int

SET NOCOUNT ON
IF (@PartyId Is Null) OR (@Qntty Is Null) OR (@RetailSum Is Null)
BEGIN
	SELECT @intErrCode = 1, @strMsg = 'Неправильные параметры в вызове процедуры ' + Object_Name(@@Procid) + ' !'
	RAISERROR (@strMsg, 11, 1)
	RETURN @intErrCode
END

SELECT @orgDocId = DocId, @orgPartyId = PartyId, @orgQntty = Qntty
FROM [CA].[GoodsDocLines]
WHERE Id = @Original_Id AND MD = @Original_MD

IF (@@rowcount <> 1)
BEGIN
	SELECT @intErrCode = 2, 
	@strMsg = 'Данные изменены после последнего запроса!'
	RAISERROR (@strMsg, 11, 1)
	RETURN @intErrCode
END

IF  @orgPartyId <> @PartyId 
BEGIN
	SELECT @intErrCode = 3, 
	@strMsg = 'Нельзя менять партию в строке возврата!'
	RAISERROR (@strMsg, 11, 1)
	RETURN @intErrCode
END

IF (@Qntty <=0) OR (@RetailSum <=0)
BEGIN
	SELECT @intErrCode = 4, @strMsg = 'Количество и сумма д.б. больше нуля !'
	RAISERROR (@strMsg, 11, 1)
	RETURN @intErrCode
END

SELECT @intDocTypeId = DocTypeId, @intDocContragentId = ContragentId, @datDocDate = DocDate
FROM [CA].[Documents] WHERE Id = @orgDocId
IF (@intDocTypeId Is Null)
BEGIN
	SELECT @intErrCode = 5, @strMsg = 'Не найден документ с идентификатором ' + cast(@orgDocId as varchar(20)) + ' !'
	RAISERROR (@strMsg, 11, 1)
	RETURN @intErrCode
END

IF (@intDocTypeId <> 8)
BEGIN
	SELECT @intErrCode = 6, @strMsg = 'Неправильный тип документа с идентификатором ' + cast(@orgDocId as varchar(20)) + ' !'
	RAISERROR (@strMsg, 11, @intErrCode)
	RETURN @intErrCode
END

IF (@intDocContragentId Is Null)
BEGIN
	SELECT @intErrCode = 7, @strMsg = 'Не указан контрагент в документе с идентификатором ' + cast(@orgDocId as varchar(20)) + ' !'
	RAISERROR (@strMsg, 11, 1)
	RETURN @intErrCode
END

SELECT @intInputLineId = P.InputLineId, @intInputDocId = I.DocId, 
@intDocTypeId = D.DocTypeId, @intPartyContragentId = I.ContragentId,
@datInputDocDate = D.DocDate
FROM CD.Parties AS P INNER JOIN CD.InputLines AS I ON P.InputLineId = I.Id 
INNER JOIN CA.Documents AS D ON I.DocId = D.Id --приходный документ
WHERE P.Id = @PartyId --возвращяемая партия

IF (@intDocContragentId <> @intPartyContragentId) AND (@intDocTypeId = 2)
BEGIN  --проверка для приходных накладных от поставщиков
	SELECT @intErrCode = 8, @strMsg = 'Контрагент по документу не соответствует контрагенту по строке!'
	RAISERROR (@strMsg, 11, 1)
	RETURN @intErrCode
END

IF @datDocDate < @datInputDocDate 
BEGIN
	SELECT @intErrCode = 9, @strMsg = 'Дата расходного документа меньше даты приходного документа!'
	RAISERROR (@strMsg, 11, 1)
	RETURN @intErrCode
END

--проверка товародвижения
SET @intRet = (-1) * (@Qntty + @orgQntty)
IF @intRet < 0 --новое количество больше старого
BEGIN
	EXEC @intRet = dbo.CheckPartyFlow @orgPartyId, @intRet, @datDocDate, @intInputCount OUTPUT, @intOutputCount OUTPUT
	IF @intRet <> 0 RETURN @intRet
END	

SELECT @ReturnLineId = L.Id
FROM [CA].[GoodsDocLines] L INNER JOIN CD.Parties P ON L.PartyId = P.Id AND L.DocId = P.DocId
WHERE P.DocId = @intInputDocId AND P.InputLineId = @intInputLineId

EXEC [dbo].[ProcessStatistic] @Note OUTPUT, @MD OUTPUT, @MW OUTPUT

	SET NOCOUNT OFF;
UPDATE [CA].[GoodsDocLines] SET 
[PartyId] = @PartyId, [Qntty] = 0 - @Qntty, [RetailSum] = 0.0 - @RetailSum, ReturnLineId = @ReturnLineId,
[Note] = @Note, [MD] = @MD, [MW] = @MW 
WHERE Id = @Original_Id;

SELECT L.Id, L.DepartmentId, L.DocId, L.PartyId, 
L.Qntty * (-1) AS Qntty, L.RetailSum * (-1.0) AS RetailSum, L.ReturnLineId,
L.Note, L.MD, L.MW 
FROM CA.GoodsDocLines AS L WHERE L.Id = @Original_Id

RETURN 0